<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use think\Db;

class CourseManage extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

    public function calendar()
    {
        $dateStart = $this->request->get('date_start');
        $dateEnd = $this->request->get('date_end');
        $filter = '';
        $params = [];
        if ($dateStart) {
            $filter .= " AND t.date >= :ds";
            $params['ds'] = $dateStart;
        }
        if ($dateEnd) {
            $filter .= " AND t.date <= :de";
            $params['de'] = $dateEnd;
        }

        try {
            $schoolSql = "SELECT 
            t.id,
            t.classes_id,
            c.name AS title,
            COALESCE(teacher.name, '待安排') AS teacher,
            COALESCE(o.name, o2.name, '') AS location,
            t.start_time,
            t.end_time,
            t.date,
            CASE 
              WHEN CONCAT(t.date,' ', t.start_time, ':00') <= NOW() AND CONCAT(t.date,' ', t.end_time, ':00') >= NOW() THEN 'ongoing'
              WHEN CONCAT(t.date,' ', t.end_time, ':00') < NOW() THEN 'completed'
              ELSE 'upcoming'
            END AS status
          FROM fa_course_table_autoplan t
          LEFT JOIN eb_classes c ON c.id = t.classes_id
          LEFT JOIN eb_class_teacher teacher ON teacher.classes_id = c.id
          LEFT JOIN fa_ocation o ON o.id = t.ocation_id
          LEFT JOIN fa_ocation o2 ON o.pid = o2.id
          WHERE t.status = 1 AND t.table_type = 1" . $filter . "
          ORDER BY t.date ASC, t.start_time ASC";

            $communitySql = "SELECT 
            t.id,
            t.classes_id,
            oc.name AS title,
            COALESCE(teacher.name, '待安排') AS teacher,
            COALESCE(o.name, o2.name, '') AS location,
            t.start_time,
            t.end_time,
            t.date,
            CASE 
              WHEN CONCAT(t.date,' ', t.start_time, ':00') <= NOW() AND CONCAT(t.date,' ', t.end_time, ':00') >= NOW() THEN 'ongoing'
              WHEN CONCAT(t.date,' ', t.end_time, ':00') < NOW() THEN 'completed'
              ELSE 'upcoming'
            END AS status
          FROM fa_course_table_autoplan t
          LEFT JOIN fa_ocation_class oc ON oc.id = t.classes_id
          LEFT JOIN eb_class_teacher teacher ON teacher.classes_id = oc.id
          LEFT JOIN fa_ocation o ON o.id = t.ocation_id
          LEFT JOIN fa_ocation o2 ON o.pid = o2.id
          WHERE t.status = 1 AND t.table_type = 2" . $filter . "
          ORDER BY t.date ASC, t.start_time ASC";

            $schoolRows = $params ? Db::query($schoolSql, $params) : Db::query($schoolSql);
            $communityRows = $params ? Db::query($communitySql, $params) : Db::query($communitySql);

            $format = function ($rows) {
                $out = [];
                foreach ($rows as $r) {
                    $out[] = [
                        'id' => intval($r['id']),
                        'title' => (string)$r['title'],
                        'teacher' => (string)$r['teacher'],
                        'location' => (string)$r['location'],
                        'time' => substr($r['start_time'], 0, 5) . '-' . substr($r['end_time'], 0, 5),
                        'date' => (string)$r['date'],
                        'status' => (string)$r['status']
                    ];
                }
                return $out;
            };

            $data = [
                'school' => $format($schoolRows),
                'community' => $format($communityRows),
                'external' => $format($communityRows)
            ];
            return json(['code' => 200, 'msg' => 'success', 'data' => $data]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    public function query()
    {
        @file_put_contents($_SERVER["DOCUMENT_ROOT"]."/../course_query.log", json_encode($_GET).PHP_EOL, FILE_APPEND);
        $scopeType = $this->request->get('scope_type');
        $scopeId = $this->request->get('scope_id');
        $teachMode = $this->request->get('teach_mode');
        $dateStart = $this->request->get('date_start');
        $dateEnd = $this->request->get('date_end');
        try {
            $where = ['status' => 1];
            if ($dateStart) $where['start_time'] = ['>=', $dateStart];
            if ($dateEnd) $where['end_time'] = ['<=', $dateEnd];
            if ($scopeType === 'school' && $scopeId) $where['school_id'] = intval($scopeId);
            if ($teachMode && $teachMode !== 'all') $where['teach_mode'] = $teachMode;
            $rows = Db::name('course_lesson')->where($where)->field('start_time as date,name,school_id,class_id')->order('start_time desc')->limit(200)->select();
            return json(['code' => 200, 'msg' => 'OK', 'data' => $rows]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }

    public function detail()
    {
        $lessonId = $this->request->get('lesson_id');
        try {
            if (!$lessonId) return json(['code' => 0, 'msg' => 'lesson_id不能为空']);
            $lesson = Db::name('course_lesson')->where('id', $lessonId)->find();
            if (!$lesson) return json(['code' => 0, 'msg' => '不存在']);
            $checkinCount = Db::name('course_attendance')->where('lesson_id', $lessonId)->count();
            $evaluationCount = Db::name('course_evaluation')->where('lesson_id', $lessonId)->count();
            $evaluations = Db::name('course_evaluation')->where('lesson_id', $lessonId)->field('user_id,username,content,create_time')->order('id desc')->limit(200)->select();
            $images = Db::name('course_image')->where('lesson_id', $lessonId)->field('url')->select();
            $detail = [
                'lesson' => $lesson,
                'checkin' => $checkinCount,
                'evaluation' => $evaluationCount,
                'evaluation_list' => $evaluations,
                'images' => $images
            ];
            return json(['code' => 200, 'msg' => 'OK', 'data' => $detail]);
        } catch (\Exception $e) {
            return json(['code' => 500, 'msg' => $e->getMessage(), 'data' => []]);
        }
    }
}